/*
   Copyright 2010 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package org.latestbit.smartobjects.examples.android.chat.client;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;

import org.latestbit.smartobjects.IRemoteSmartObjectAvailabilityListener;
import org.latestbit.smartobjects.examples.chat.*;

public class ChatClientImpl implements IRemoteSmartObjectAvailabilityListener<IChatService> {

	private IChatService service;
	private CommandLineOptions options;

	private ChatEventsSkeleton eventsCallbackSkeleton = null;
	private boolean disconnected = true;
	private IChatSession session;

	public ChatClientImpl(CommandLineOptions options, IChatService service, IChatEventsSyncSmartObject chatRoomNotificationsHandler) throws Exception {
		this.service = service;
		this.options = options;
		this.eventsCallbackSkeleton = new ChatEventsSyncSkeleton( chatRoomNotificationsHandler );
	}	

	protected String readTextLine(String prompt) {
		String result = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		try {
			System.out.print(prompt);
			result = br.readLine();
		} 
		catch (IOException ioe) {
			
		}
		return result;
	}

	public void start() throws Exception {
		
		this.session = this.service.enterToChat(
				options.getLogin(), options.getPassword(), eventsCallbackSkeleton
		);
		disconnected = false;
		this.service.addAvailabilityListener(this);				
	}

	public void sendUserInput(String text) {
		if(this.session!=null && text!=null && text.trim()!="") {
			try {
				this.session.sendMessage(new ChatMessage(text));
			}
			catch(Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	@Override
	public void onAvailable(IChatService object) {
		System.out.println();
		System.out.println("[I] Connected!");
		disconnected = false;
	}

	@Override
	public void onUnavailable(IChatService object) {
		if(!disconnected) {
			System.out.println();
			System.out.println("[SM] Disconnected. Please enter to exit");
			disconnected = true;
		}
	}

}
